const crypto = require('crypto');

const AES_KEY_LENGTH = 16;

/**
 * AES-GCM 加密
 * @param {string} text 需要加密的文本
 * @param {string} key 16 位密钥
 */
function aesEncrypt(text, key) {
  const iv = crypto.randomBytes(12); // GCM 使用 12 字节 IV
  const cipher = crypto.createCipheriv('aes-128-gcm', Buffer.from(key, 'utf8'), iv);
  let encrypted = cipher.update(text, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  const authTag = cipher.getAuthTag().toString('base64');
  return {
    iv: iv.toString('base64'),
    encryptedData: encrypted + authTag // 合并加密数据和认证标签
  };
}

/**
 * AES-GCM 解密
 * @param {string} encryptedData 加密文本（包含认证标签）
 * @param {string} key 16 位密钥
 * @param {string} iv IV 向量（Base64 编码）
 */
function aesDecrypt(encryptedData, key, iv) {
  // 分离加密数据和认证标签
  const authTagLength = 16; // GCM 认证标签固定 16 字节
  const encryptedBuffer = Buffer.from(encryptedData, 'base64');
  const authTag = encryptedBuffer.slice(-authTagLength); // 最后 16 字节是认证标签
  const encrypted = encryptedBuffer.slice(0, -authTagLength); // 前面是加密数据

  const decipher = crypto.createDecipheriv('aes-128-gcm', Buffer.from(key, 'utf8'), Buffer.from(iv, 'base64'));
  decipher.setAuthTag(authTag);
  let decrypted = decipher.update(encrypted, null, 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

module.exports = { aesEncrypt, aesDecrypt };
